// server.go
package main

import (
	"encoding/binary"
	"flag"
	"fmt"
	"github.com/sirupsen/logrus"
	"net"
)

func main() {
	// 解析命令行参数
	port := flag.Int("port", 8080, "TCP server port")
	flag.Parse()

	// 初始化 Logrus
	log := logrus.New()
	log.SetFormatter(&logrus.TextFormatter{
		FullTimestamp: true,
	})
	log.SetLevel(logrus.InfoLevel)

	// 监听 TCP 端口
	addr := fmt.Sprintf(":%d", *port)
	listener, err := net.Listen("tcp", addr)
	if err != nil {
		log.Fatalf("Failed to start server on port %d: %v", *port, err)
	}
	defer listener.Close()
	log.Infof("Server listening on %s", addr)

	for {
		// 接受客户端连接
		conn, err := listener.Accept()
		if err != nil {
			log.Errorf("Failed to accept connection: %v", err)
			continue
		}
		log.Infof("New client connected: %s", conn.RemoteAddr().String())

		// 处理客户端连接
		go handleConnection(conn, log)
	}
}

func handleConnection(conn net.Conn, log *logrus.Logger) {
	defer conn.Close()

	// 读取消息
	for {
		// 读取 4 字节的消息长度头
		lengthBuf := make([]byte, 4)
		_, err := conn.Read(lengthBuf)
		if err != nil {
			log.Errorf("Failed to read message length: %v", err)
			return
		}

		// 解析消息长度
		length := binary.BigEndian.Uint32(lengthBuf)
		if length == 0 {
			log.Warn("Received empty message")
			return
		}

		// 读取消息内容
		message := make([]byte, length)
		_, err = conn.Read(message)
		if err != nil {
			log.Errorf("Failed to read message: %v", err)
			return
		}

		log.Infof("Received message: %s", string(message))

		// 构造响应
		response := "Server received: " + string(message)
		respLen := uint32(len(response))

		// 发送响应：4 字节长度 + 消息内容
		respBuf := make([]byte, 4+len(response))
		binary.BigEndian.PutUint32(respBuf[0:4], respLen)
		copy(respBuf[4:], response)

		// 发送响应
		_, err = conn.Write(respBuf)
		if err != nil {
			log.Errorf("Failed to send response: %v", err)
			return
		}
		log.Infof("Sent response: %s", response)
	}
}
